import _ from 'lodash'
import { JSEncrypt } from 'jsencrypt'
import { useWebsiteStore } from '@/store/modules/website.js'
import katex from 'katex'

export function cloneDeep(obj) {
  //return JSON.parse(JSON.stringify(obj))
  return _.cloneDeep(obj)
}

export function toObj(attr) {
  const obj = {}
  if (attr) {
    for (let i = 0; i < attr.length; i++) {
      obj[attr[i].code] = attr[i].desc
    }
  }
  return obj
}

export function changeNumToEn(num) {
  return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')[num]
}

// 字符串转数字类型
export function toNumber(str) {
  if (str === '') {
    return 0
  }
  return Number(str)
}

/**
 * 数字转汉字（限制不大于100）
 * @param {number|string} num
 */
export const numToChinese = (num) => {
  num = typeof num === 'number' ? String(num) : num
  const changeNum = ['零', '⼀', '二', '三', '四', '五', '六', '七', '⼋', '九']
  if (num.length === 1) {
    return changeNum[num]
  } else if (num.length === 2) {
    if (num % 10 === 0) {
      return num / 10 === 1 ? '十' : changeNum[num / 10] + '十'
    } else {
      const numArr = num.split('')
      if (num < 20) {
        return '十' + changeNum[numArr[1]]
      } else {
        return changeNum[numArr[0]] + '十' + changeNum[numArr[1]]
      }
    }
  } else {
    return '一百'
  }
}

/**
 * 格式化时长
 * @param time
 */
export function formatTime(time) {
  let a = ~~(time / 3600)
  let b = ~~(time / 60) - a * 60
  let c = time % 60
  a = String(a).padStart(2, '0')
  b = String(b).padStart(2, '0')
  c = String(c).padStart(2, '0')
  if (a === '00') {
    return `${b}:${c}`
  } else {
    return `${a}:${b}:${c}`
  }
}

// 文件大小转换
export function transformSize(bytes) {
  // 文件大小转换
  const bt = parseInt(bytes)
  let result
  if (bt === 0) {
    result = '0B'
  } else {
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    const i = Math.floor(Math.log(bt) / Math.log(k))
    if (typeof i !== 'number') {
      result = '-'
    } else {
      result = (bt / Math.pow(k, i)).toFixed(2) + sizes[i]
    }
  }
  return result
}

/**
 * 使用katex渲染公式
 * @param value
 * @param element
 */
export function katexRender(value, element) {
  if (!element) return
  katex.render(value, element, {
    throwOnError: false
  })
}

export function encrypt(password, publicKey) {
  if (!publicKey) {
    publicKey = useWebsiteStore().getInfo.rsaLoginPublicKey
  }
  const crypt = new JSEncrypt()
  crypt.setPublicKey(publicKey)
  return crypt.encrypt(password)
}
